<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Action
 *
 * @author bom
 */
class My_Controller_Action extends Zend_Controller_Action
{

	//put your code here
	public function loadModel($moduleName, $className)
	{
		$modelDir = $this->getFrontController()->getModuleDirectory($moduleName)
				. DIRECTORY_SEPARATOR . 'models';

		Zend_Loader::loadClass($className, $modelDir);

		// if we got here - then file is included
		return new $className();
	}

	public function init()
	{
		$this->_errorMessenger = new Zend_Controller_Action_Helper_FlashMessenger();
		$this->_errorMessenger->setActionController($this)->init();
		$this->_errorMessenger->setNamespace('error');
		$this->_notifyMessenger = new Zend_Controller_Action_Helper_FlashMessenger();
		$this->_notifyMessenger->setActionController($this)->init();
		$this->_notifyMessenger->setNamespace('error');
		$this->auth = Zend_Auth::getInstance();
		$this->postData = new Zend_Session_Namespace("postData");

		$module = $this->_request->getModuleName();
		$controller = $this->_request->getControllerName();
		$action = $this->_request->getActionName();

		$url = new Zend_Session_Namespace("url");
		$url->return = $this->getUrl(array("module" => $module, "controller" => $controller, "action" => $action));


		if(($module != "user" || $controller != "account" || ($action != "login" && $action != "loginpost")) && ($module != "checkout" || $controller != "cart" || $action != "update"))
		{
			$session = new Zend_Session_Namespace('lastRequest');
			$session->lastRequestUri = Zend_Controller_Front::getInstance()->getRequest()->getRequestUri();
		}

		// login facebook
		$session = new Zend_Session_Namespace('fb');
		if($this->_request->getParam("fb") == "true")
		{
			$session->login = true;
		}
		$cookie = $this->get_facebook_cookie(Zend_Registry::get('fb_appId'), Zend_Registry::get('fb_secret'));
		if($cookie)
		{
			if(isset($session->login) && $session->login)
			{
				$user;
				$user->username = "facebooker";
				$user->fullname = "facebooker";
				$user->group_id = 2;
				$auth = Zend_Auth::getInstance();
				$auth->getStorage()->write($user);
			}
			Zend_Registry::set("fb_login", 1);
		}
		else
		{
			Zend_Registry::set("fb_login", 0);
		}
	}

	private function get_facebook_cookie($app_id, $application_secret)
	{
		if(!isset($_COOKIE['fbs_' . $app_id]))
		{
			return null;
		}

		$args = array();
		parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
		ksort($args);
		$payload = '';
		foreach($args as $key => $value)
		{
			if($key != 'sig')
			{
				$payload .= $key . '=' . $value;
			}
		}
		if(md5($payload . $application_secret) != $args['sig'])
		{
			return null;
		}
		return $args;
	}
	/*
	 * get Url without base url and language
	 */

	protected function getUrl($arr)
	{
		$default_language = Zend_Registry::get("default_language");
		$base_url = $this->view->baseUrl();
		$redirect_url = $this->view->url($arr);
		$redirect_url = str_replace($base_url, "", $redirect_url);
		$redirect_url = str_replace("/index.php", "", $redirect_url);
		$redirect_url = str_replace("/$default_language/", "/", $redirect_url);
		return $redirect_url;
	}

	public function sendmail($data, $param, $template, $content=null)
	{
		$this->view->param = $param;
		$this->view->data = $data;

		$myview = new Zend_View();
		$myview->setScriptPath(APPLICATION_PATH . DIRECTORY_SEPARATOR . 'layouts' . DIRECTORY_SEPARATOR . 'mail');

		if($content != null)
		{
			$keys = array_keys($content);
			foreach($keys as $key)
			{
				$myview->assign($key, $content[$key]);
			}
		}

		$data['body'] = $myview->render($template);

		$mail = new Zend_Mail('utf-8');
		$mail->setBodyHtml($data['body']);
		$mail->setFrom($data['fmail'], $data['fname']);
		$mail->addTo($data['tmail'], $data['tname']);
		$mail->setSubject($data['subject']);

		try
		{
			$mail->send();
		}
		catch(Exception $ex)
		{
			$this->sendsmtp($data, $param, $template);
		}
	}

	public function sendsmtp($data, $param, $template)
	{
		$options = array(
			'auth' => 'login',
			'username' => 'doductai@gmail.com',
			'password' => 'mayhamam',
			'ssl' => 'tls',
			'port' => 587
		);
		$mailTransport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $options);
		Zend_Mail::setDefaultTransport($mailTransport);

		$m = new Zend_Mail('utf-8');
		$m->addTo($data['tmail']);
		$m->setFrom($data['fmail'], $data['fname']);
		$m->setSubject($data['subject']);
		$m->setBodyHtml($data['body']);
		$m->send();
	}

	public function genPassword($len = 6)
	{
		$r = '';
		for($i = 0; $i < $len; $i++)
			$r .= chr(rand(0, 25) + ord('a'));
		return $r;
	}

	public function isAccess($group_id, $control_id)
	{
		$control_id .= "";

		$model = $this->loadModel("admin_user", "Group");
		$group = $model->getGroupById($group_id);
		$role = explode(";", $group["role"]);
		if(array_search($control_id, $role) === false)
		{
			return false;
		}
		return true;
	}

	public function sendCheckoutSuccessMail($order)
	{
		$itemModel = $this->loadModel('admin_cms', 'Item');
		$shippingModel = $this->loadModel('admin_cms', 'ShippingAddress');
		$order_type = $this->loadModel('cms', 'OrderType');
		
		$content = array();
		$content["items"] = $itemModel->fetchAll($itemModel->select()->where('order_id=?', $order->order_id));
		$content["shipping"] = $shippingModel->fetchRow($shippingModel->select()->where('address_id=?', $order->address_id));
		$tmp = $order_type->fetchRow($order_type->select()->where("order_type_id=?", $content["shipping"]->order_type_id));
		$content["payment"] = $tmp["name"];
		
		$content["subtotal"] = 0;
		foreach($content["items"] as $item)
		{
			$content["subtotal"] += $item->row_total;
		}
		
		$content["baseurl"] = (@$_SERVER["HTTPS"] == "on") ? "https//:" : "http://";
		$content["baseurl"] .= $_SERVER["SERVER_NAME"] . $this->view->baseUrl("index.php");
		
		// send mail
        $data = array(
            'subject' => "Đăng ký mua hàng thành công - HỢP MUA",
            'fmail' => 'info@hopmua.com',
            'fname' => 'admin',
            'tmail' => $content["shipping"]["email"],
            'tname' => $content["shipping"]["name"]
        );
        $this->sendmail($data, '', 'checkoutsuccess.html', $content);
	}
	
	public function editOrderStatus($orderId, $status)
	{
		$model = $this->loadModel("admin_cms", "Order");
		$order = $model->getOrderById($orderId);
		if($order->status == $status)
		{
			return;
		}
		else
		{
			$order->status = $status;
			$order->save();
			if($status != 3)
			{
				return;
			}
		}
		
		// send mail checkout success
		$this->sendCheckoutSuccessMail($order);
		
		// check get good deal

		// get items by orderId
		$model = $this->loadModel("admin_cms", "Item");
		$items = $model->getItemsByOrderId($orderId);

		// get complete deals
		$model = $this->loadModel('cms', 'CmsDeal');
		$goodDeals = array();
		foreach($items as $item)
		{
			$this->GenBarCode($item->item_id, $item->deal_id);
			$deal = $model->getDealById($item->deal_id);
			$deal_quantity = $deal->deal_quantity;

			$item_quantity = $item->quantity;
			
			$count_deal = $model->countCompleteSoldDeal($item->deal_id) - $item_quantity; // ko tính item quantity của order vừa cập nhật

			if($count_deal + $item_quantity >= $deal_quantity) // get good deal
			{
				$goodDeal = array("deal_id" => $item->deal_id, "deal_title" => $item->deal_title);
				
				$goodDeal["all"] = false;
				if($count_deal < $deal_quantity) // vừa đạt giá tốt
				{
					$goodDeal["all"] = true;
				}
				
				$goodDeals[] = $goodDeal;
			}
		}

		// get information to mail
		$model = $this->loadModel("admin_cms", "ShippingAddress");
		$emails = array();
		foreach($goodDeals as $goodDeal)
		{
			$email = array();
			
			if($goodDeal['all'])
			{
				$addresses = $model->getShippingAddressByDealId($goodDeal['deal_id']);
				foreach($addresses as $address)
				{
					$email["email"] = $address->email;
					$email["name"] = $address->name;
					$email["deal_title"] = $goodDeal["deal_title"];
					$email["deal_id"] = $goodDeal['deal_id'];
					$emails[] = $email;
				}
			}
			else
			{
				$address = $model->getShippingAddressById($order->address_id);

				$email["email"] = $address->email;
				$email["name"] = $address->name;
				$email["deal_title"] = $goodDeal["deal_title"];
				$email["deal_id"] = $goodDeal['deal_id'];
				$emails[] = $email;
			}
		}

		// send mail get good deal
		foreach($emails as $email)
		{
			$link = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
			$link .= $_SERVER["SERVER_NAME"] . $this->view->baseUrl("/index.php/cms/index/deal/id/{$email['deal_id']}");

			$data = array(
				'subject' => "{$email['deal_title']} đạt giá tốt",
				'fmail' => 'info@hopmua.com',
				'fname' => 'admin',
				'tmail' => $email['email'],
				'tname' => $email['name']
			);
			$content = array("url" => $link);
			$this->sendmail($data, '', 'getgooddeal.html', $content);
		}
	}
	
	//update barcode to orderitem
	function GenBarCode($order_id, $deal_id) {
		$barCode = "";
		$arrayBarCode = array();
		
		//update current BarCode = $currentBarCode;
		$dealModel = $this->loadModel('admin_cms', 'Deal');
		$deal = $dealModel->getDealById($deal_id);
		
		//update $barCode to Item;
		$orderModel = $this->loadModel("admin_cms", "Item");
		$item = $orderModel->getItemById($order_id);
		
		//update if there is not a barcode	
		if($item->barcode == NULL || $item->barcode == '') {					
			//Set barcode to an order item
			$currentBarCode = $deal->current_barcode;
			
			for($quantity = 0; $quantity < $deal->deal_quantity; $quantity++) {
				$currentBarCode++;
				
				array_push($arrayBarCode, $this->GenZeroNumber($currentBarCode, 8));
			}
			
			$barCode = implode($arrayBarCode, '|');
			
			$item->barcode = $barCode;
			$deal->current_barcode = $currentBarCode;			
			
			$item->save();			
			$deal->save();
		}
	}
	
	function GenZeroNumber($currentBarCode, $length) {		
		$len = strlen($currentBarCode);		
		if($len < $length) {		
			$zero = '';
			for($i = 0; $i < $length - $len; $i++) {
				$zero .= '0';
			}
			return $zero . $currentBarCode;
		}
		return $currentBarCode;
	}
}
?>
